package top.vchao.mywebview;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.webkit.WebSettings;
import android.webkit.WebView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import top.vchao.mywebview.utils.CommonUtil;
import top.vchao.mywebview.utils.LogUtils;
import top.vchao.mywebview.utils.ToastUtil;

public class WebViewActivity extends Activity {

    @BindView(R.id.webview)
    WebView webview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        ButterKnife.bind(this);

        initWebView(webview);
    }

    private void initWebView(WebView webview) {
        MyWebViewClient myWebViewClient = new MyWebViewClient();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);//设置js可以直接打开窗口，如window.open()，默认为false
        webview.getSettings().setJavaScriptEnabled(true);//是否允许执行js，默认为false。设置true时，会提醒可能造成XSS漏洞
        webview.getSettings().setSupportZoom(false);//是否可以缩放，默认true
        webview.getSettings().setBuiltInZoomControls(false);//是否显示缩放按钮，默认false
        webview.getSettings().setUseWideViewPort(true);//设置此属性，可任意比例缩放。大视图模式
        webview.getSettings().setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题
// webview.getSettings().setUserAgentString("User-Agent:Android");//设置用户代理，一般不用
        webview.addJavascriptInterface(new JavaScriptinterface(WebViewActivity.this),
                "android");
//      settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLAW);
        webview.setWebChromeClient(new MyWebChromeClient());
        webview.setWebViewClient(myWebViewClient);

//        缓存
        webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);//不支持缓存
        webview.getSettings().setAppCacheEnabled(false);//是否使用缓存
        webview.getSettings().setDomStorageEnabled(false);//DOM Storage
        webview.getSettings().setDatabaseEnabled(false);//开启 database storage API 功能

        //添加请求头
//        Map<String, String> extraHeaders = new HashMap<String, String>();
//        extraHeaders.put("token", "token");

//        webview.loadUrl("file:///android_asset/index.html");

//        webview.loadUrl("http://123.206.23.143/yzb/index.html", extraHeaders);
        webview.loadUrl("http://123.206.23.143/yzb/index.html");

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //权限申请成功
                obtionContacts();
            } else {
                ToastUtil.showShort( "获取联系人的权限申请失败");
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void obtionContacts() {
        Uri uri = Uri.parse("content://contacts/people");
        Intent intent = new Intent(Intent.ACTION_PICK, uri);
        startActivityForResult(intent, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0:
                if (data == null) {
                    return;
                }
                //处理返回的data,获取选择的联系人信息
                Uri uri = data.getData();
                String[] contacts = getPhoneContacts(uri);

                LogUtils.e("姓名：" + contacts[0]);
                LogUtils.e("手机号：" + contacts[1]);
//                wvValueAddService.loadUrl("javascript:" + pic_js + "('" + str + "')");
                webview.loadUrl("javascript:displayContact('" + contacts[0] + "','" + contacts[1] + "')");
                break;
        }

    }

    private String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                contact[1] = CommonUtil.getNum(contact[1]);

            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }
}
